package com.fuli.app.common;

import com.fuli.app.dao.UserDao;
import com.fuli.app.entity.User;
import com.fuli.app.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class fuliRealm extends AuthorizingRealm {
    @Autowired
    private UserDao userDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("开始授权");
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> roles = new HashSet<>();
        if (user != null)
            roles.add(user.getRole());
        authorizationInfo.setRoles(roles);
        System.out.println("授权成功");
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("开始认证");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String account = token.getUsername();
        User user = userDao.findByAccount(account);
        if (user == null)
            throw new UnknownAccountException("账号不存在！");
        if (!user.getPassword().equals(token.getPassword()))
            throw new AccountException("密码不匹配");
        SecurityUtils.getSubject().getSession().setTimeout(1000 * 60 * 60);
        SecurityUtils.getSubject().getSession().setAttribute("user", user);
        System.out.println("认证成功");

        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}
